package com.superman.daoImpl;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.superman.dao.CategoryDao;
import com.superman.domain.Category;
import com.superman.utils.JDBCUtils;

public class CategoryDaoImpl implements CategoryDao {
	private QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
	@Override
	public void add(Category category) {
		String sql = "insert into category (cid,cname) values (?,?)";
		try {
			qr.update(sql, category.getCid(),category.getCname());
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException("添加种类失败");
		}
	}
	@Override
	public List<Category> findAllCategory() {
		String sql = "select * from category";
		try {
			return qr.query(sql, new BeanListHandler<Category>(Category.class));
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException("显示所有种类失败");
		}
	}
	
	@Override
	public Category findById(String cid) {
		String sql = "select * from category where cid=?";
		try {
			return qr.query(sql, new BeanHandler<Category>(Category.class), cid);
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException("查询指定类别失败");
		}
	}
	@Override
	public void updateCategory(String cid,String cname) {
		String sql = "update category set cname=? where cid=?";
		try {
			qr.update(sql, cname,cid);
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException("修改指定类别失败");
		}
	}
	@Override
	public void remove(String cid) {
		// TODO Auto-generated method stub
		
	}
	QueryRunner queryRunner = new QueryRunner();
	@Override
	public void remove(Connection conn, String cid) {
		String sql = "delete from category where cid=?";
		try {
			queryRunner.update(conn, sql, cid);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("删除指定类别失败");
		}
	}

}
